# 目标管理路由
from flask import Blueprint, render_template, request, jsonify
from models import db
from models.goal import Goal, GoalTask, Milestone, Reflection
from datetime import datetime

goal_bp = Blueprint('goal', __name__, url_prefix='/goal')

@goal_bp.route('/')
def list_goals():
    """显示目标管理页面"""
    return render_template('goal.html')

@goal_bp.route('/api/goals', methods=['GET'])
def get_goals():
    """获取目标列表（实时计算进度）"""
    status = request.args.get('status')
    category = request.args.get('category')
    
    query = Goal.query
    
    if status:
        query = query.filter_by(status=status)
    
    if category:
        query = query.filter_by(category=category)
    
    goals = query.order_by(Goal.created_at.desc()).all()
    
    # 实时计算每个目标的进度
    for goal in goals:
        if len(goal.tasks) > 0:
            completed_count = sum(1 for task in goal.tasks if task.completed)
            new_progress = int((completed_count / len(goal.tasks)) * 100)
            
            # 如果进度有变化，更新数据库
            if goal.progress != new_progress or (new_progress == 100 and goal.status == '进行中') or (new_progress < 100 and goal.status == '已完成'):
                update_goal_progress(goal.id)
    
    # 重新查询以获取最新数据
    goals = query.order_by(Goal.created_at.desc()).all()
    
    return jsonify({
        'goals': [goal.to_dict() for goal in goals]
    })

@goal_bp.route('/api/goals', methods=['POST'])
def create_goal():
    """创建新目标"""
    data = request.json
    
    # 解析目标日期
    target_date = None
    if data.get('target_date'):
        try:
            target_date = datetime.fromisoformat(data['target_date'].replace('Z', '+00:00'))
        except:
            pass
    
    goal = Goal(
        title=data['title'],
        description=data.get('description', ''),
        category=data.get('category', '其他'),
        target_date=target_date
    )
    
    db.session.add(goal)
    db.session.commit()
    
    return jsonify({
        'success': True,
        'goal': goal.to_dict()
    }), 201

@goal_bp.route('/api/goals/<int:goal_id>', methods=['GET'])
def get_goal(goal_id):
    """获取目标详情（实时计算进度）"""
    goal = Goal.query.get_or_404(goal_id)
    
    # 实时计算并更新进度
    update_goal_progress(goal_id)
    
    # 重新查询以获取最新数据
    goal = Goal.query.get(goal_id)
    
    data = goal.to_dict()
    data['tasks'] = [task.to_dict() for task in goal.tasks]
    data['milestones'] = [milestone.to_dict() for milestone in goal.milestones]
    data['reflections'] = [reflection.to_dict() for reflection in goal.reflections]
    
    return jsonify(data)

@goal_bp.route('/api/goals/<int:goal_id>', methods=['PUT'])
def update_goal(goal_id):
    """更新目标"""
    goal = Goal.query.get_or_404(goal_id)
    data = request.json
    
    if 'title' in data:
        goal.title = data['title']
    if 'description' in data:
        goal.description = data['description']
    if 'category' in data:
        goal.category = data['category']
    if 'status' in data:
        goal.status = data['status']
    if 'progress' in data:
        goal.progress = max(0, min(100, data['progress']))  # 限制在0-100
    if 'target_date' in data:
        try:
            goal.target_date = datetime.fromisoformat(data['target_date'].replace('Z', '+00:00'))
        except:
            pass
    
    db.session.commit()
    
    return jsonify({
        'success': True,
        'goal': goal.to_dict()
    })

@goal_bp.route('/api/goals/<int:goal_id>', methods=['DELETE'])
def delete_goal(goal_id):
    """删除目标"""
    goal = Goal.query.get_or_404(goal_id)
    db.session.delete(goal)
    db.session.commit()
    
    return jsonify({
        'success': True,
        'message': '删除成功'
    })

@goal_bp.route('/api/goals/<int:goal_id>/tasks', methods=['POST'])
def add_task(goal_id):
    """添加子任务"""
    goal = Goal.query.get_or_404(goal_id)
    data = request.json
    
    # 获取当前最大排序号
    max_order = db.session.query(db.func.max(GoalTask.order)).filter_by(goal_id=goal_id).scalar() or 0
    
    task = GoalTask(
        goal_id=goal_id,
        title=data['title'],
        order=max_order + 1
    )
    
    db.session.add(task)
    db.session.commit()
    
    # 更新目标进度
    update_goal_progress(goal_id)
    
    return jsonify({
        'success': True,
        'task': task.to_dict()
    })

@goal_bp.route('/api/goals/<int:goal_id>/tasks/<int:task_id>', methods=['PUT'])
def update_task(goal_id, task_id):
    """更新子任务"""
    task = GoalTask.query.get_or_404(task_id)
    data = request.json
    
    if 'title' in data:
        task.title = data['title']
    if 'completed' in data:
        task.completed = data['completed']
    
    db.session.commit()
    
    # 更新目标进度
    update_goal_progress(goal_id)
    
    return jsonify({
        'success': True,
        'task': task.to_dict()
    })

@goal_bp.route('/api/goals/<int:goal_id>/tasks/<int:task_id>', methods=['DELETE'])
def delete_task(goal_id, task_id):
    """删除子任务"""
    task = GoalTask.query.get_or_404(task_id)
    db.session.delete(task)
    db.session.commit()
    
    # 更新目标进度
    update_goal_progress(goal_id)
    
    return jsonify({
        'success': True,
        'message': '删除成功'
    })

@goal_bp.route('/api/goals/<int:goal_id>/milestones', methods=['POST'])
def add_milestone(goal_id):
    """添加里程碑"""
    goal = Goal.query.get_or_404(goal_id)
    data = request.json
    
    # 解析目标日期
    target_date = None
    if data.get('target_date'):
        try:
            target_date = datetime.fromisoformat(data['target_date'].replace('Z', '+00:00'))
        except:
            pass
    
    milestone = Milestone(
        goal_id=goal_id,
        title=data['title'],
        target_date=target_date
    )
    
    db.session.add(milestone)
    db.session.commit()
    
    return jsonify({
        'success': True,
        'milestone': milestone.to_dict()
    })

@goal_bp.route('/api/goals/<int:goal_id>/milestones/<int:milestone_id>', methods=['PUT'])
def update_milestone(goal_id, milestone_id):
    """更新里程碑"""
    milestone = Milestone.query.get_or_404(milestone_id)
    data = request.json
    
    if 'title' in data:
        milestone.title = data['title']
    if 'target_date' in data:
        try:
            milestone.target_date = datetime.fromisoformat(data['target_date'].replace('Z', '+00:00'))
        except:
            pass
    if 'completed' in data:
        milestone.completed = data['completed']
        if milestone.completed:
            milestone.completed_at = datetime.utcnow()  # 已经是UTC时间，保持一致
        else:
            milestone.completed_at = None
    
    db.session.commit()
    
    return jsonify({
        'success': True,
        'milestone': milestone.to_dict()
    })

@goal_bp.route('/api/goals/<int:goal_id>/milestones/<int:milestone_id>', methods=['DELETE'])
def delete_milestone(goal_id, milestone_id):
    """删除里程碑"""
    milestone = Milestone.query.get_or_404(milestone_id)
    db.session.delete(milestone)
    db.session.commit()
    
    return jsonify({
        'success': True,
        'message': '删除成功'
    })

@goal_bp.route('/api/goals/<int:goal_id>/reflections', methods=['POST'])
def add_reflection(goal_id):
    """添加反思笔记"""
    goal = Goal.query.get_or_404(goal_id)
    data = request.json
    
    reflection = Reflection(
        goal_id=goal_id,
        content=data['content']
    )
    
    db.session.add(reflection)
    db.session.commit()
    
    return jsonify({
        'success': True,
        'reflection': reflection.to_dict()
    })

@goal_bp.route('/api/goals/<int:goal_id>/reflections/<int:reflection_id>', methods=['PUT'])
def update_reflection(goal_id, reflection_id):
    """更新反思笔记"""
    reflection = Reflection.query.get_or_404(reflection_id)
    data = request.json
    
    if 'content' in data:
        reflection.content = data['content']
    
    db.session.commit()
    
    return jsonify({
        'success': True,
        'reflection': reflection.to_dict()
    })

@goal_bp.route('/api/goals/<int:goal_id>/reflections/<int:reflection_id>', methods=['DELETE'])
def delete_reflection(goal_id, reflection_id):
    """删除反思笔记"""
    reflection = Reflection.query.get_or_404(reflection_id)
    db.session.delete(reflection)
    db.session.commit()
    
    return jsonify({
        'success': True,
        'message': '删除成功'
    })

@goal_bp.route('/api/stats', methods=['GET'])
def get_stats():
    """获取统计信息"""
    total = Goal.query.count()
    active = Goal.query.filter_by(status='进行中').count()
    completed = Goal.query.filter_by(status='已完成').count()
    abandoned = Goal.query.filter_by(status='已放弃').count()
    
    return jsonify({
        'total': total,
        'active_count': active,
        'completed': completed,
        'abandoned': abandoned
    })

@goal_bp.route('/api/goals/clear-completed', methods=['DELETE'])
def clear_completed_goals():
    """一键清除所有已完成的目标"""
    # 查询所有已完成的目标
    completed_goals = Goal.query.filter_by(status='已完成').all()
    count = len(completed_goals)
    
    # 批量删除（级联删除会自动处理相关的任务、里程碑和反思）
    for goal in completed_goals:
        db.session.delete(goal)
    
    db.session.commit()
    
    return jsonify({
        'success': True,
        'count': count,
        'message': f'成功清除 {count} 个已完成的目标'
    })

def update_goal_progress(goal_id):
    """更新目标进度（基于子任务完成情况）"""
    goal = Goal.query.get(goal_id)
    if not goal:
        return
    
    tasks = goal.tasks
    if len(tasks) == 0:
        # 没有子任务时，保持当前进度
        return
    
    completed_count = sum(1 for task in tasks if task.completed)
    progress = int((completed_count / len(tasks)) * 100)
    
    goal.progress = progress
    
    # 根据进度自动更新状态（仅当状态为"进行中"或"已完成"时）
    if goal.status in ['进行中', '已完成']:
        if progress == 100:
            goal.status = '已完成'
        else:
            # 进度小于100%，自动改回进行中
            goal.status = '进行中'
    
    db.session.commit()

